package com.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;

public class LogTool {
	private PrintWriter logPrint;
	private String logFile = "";
	private String logName = "";

	/**
	 */
	public LogTool(){
		checkDate();
	}

	/**
	 */
	public LogTool(String logName){
		this.logName = logName;
		checkDate();
	}

	/**
	 */
	private String getLogFile(){
		String date = "";
		Calendar cd = Calendar.getInstance();
		int y = cd.get(Calendar.YEAR);
		int m = cd.get(Calendar.MONTH) + 1;
		int d = cd.get(Calendar.DAY_OF_MONTH);

		date = "./log/" + logName + y + "-";

		if(m < 10)
			date += 0;

		date += m + "-";

		if(d < 10)
			date += 0;

		date += d + ".log";
		return date;
	}

	/**
	 */
	private void newLog(){
		logFile = getLogFile();

		try{
			logPrint = new PrintWriter(new FileWriter(logFile, true), true);
		}catch(IOException e){
			(new File("./log")).mkdir();

			try{
				logPrint = new PrintWriter(new FileWriter(logFile, true), true);
			}catch(IOException ex){
				logPrint = new PrintWriter(System.err);
			}
		}
	}

	/**
	 */
	private void checkDate(){
		if(logFile == null || logFile.trim().equals("") || !logFile.equals(getLogFile())){
			newLog();
		}
	}

	/**
	 */
	public void log(String msg) {
		checkDate();
		logPrint.println(new Date() + ": " + msg);
	}

	/**
	 */
	public void log(Throwable e, String msg) {
		checkDate();
		logPrint.println(new Date() + ": " + msg);
		e.printStackTrace(logPrint);
	}
}
